<!-- 用户购买(产品详情)界面 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="id" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="资金方" prop="escrow">
        <el-input  v-model="queryParams.escrow" placeholder="请输入资金方" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="productsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="资金方" align="center" prop="escrow" >
      
      </el-table-column>

      <el-table-column label="月利率" align="center" prop="monthRate" />
      <el-table-column label="咨询费率" align="center" prop="consultingRate" />
      <el-table-column label="保证金费率" align="center" prop="marginRate" />
      <el-table-column label="还款方式" align="center" prop="paymentMethod">
        <template slot-scope="scope">
          <span v-if="scope.row.paymentMethod == 0">等额本息</span>
          <span v-else-if="scope.row.paymentMethod == 1">等本等息</span>
          <span v-else-if="scope.row.paymentMethod == 2">先息后本</span>
          <span v-else-if="scope.row.paymentMethod == 3">一次性环息付本</span>
        </template>
      </el-table-column>
      <el-table-column label="贷款期限" align="center" prop="loanTerm">
        <template slot-scope="scope">
          <span v-if="scope.row.loanTerm == 1">1个月</span>
          <span v-else-if="scope.row.loanTerm == 3">3个月</span>
          <span v-else-if="scope.row.loanTerm == 6">6个月</span>
          <span v-else-if="scope.row.loanTerm == 9">9个月</span>
          <span v-else-if="scope.row.loanTerm == 12">12个月</span>
          <span v-else-if="scope.row.loanTerm == 18">18个月</span>
          <span v-else-if="scope.row.loanTerm == 24">24个月</span>
          <span v-else-if="scope.row.loanTerm == 36">36个月</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="big" type="text" @click="buy(scope.row)">购买</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      :page-sizes="[5, 10, 15, 20]" @pagination="getList" />

    <!-- 购买对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="7">
            <div class="grid-content bg-purple">
              <el-form-item label="产品名称" prop="productName">
                {{ form.productName }}
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple-light">
              <el-form-item label="资金方" prop="escrow">
                {{form.escrow}}
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7">
          </el-col>
        </el-row>

        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="7">
            <div class="grid-content bg-purple">
              <el-form-item label="月利率" prop="monthRate">
                {{ form.monthRate }}%
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple-light">
              <el-form-item label="咨询费率" prop="consultingRate">
                {{ form.consultingRate }}%
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple">
              <el-form-item label="保证费率" prop="marginRate">
                {{ form.marginRate }}%
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row type="flex" class="row-bg" justify="space-between">
          <el-col :span="7">
            <div class="grid-content bg-purple">
              <el-form-item label="还款方式" prop="paymentMethod">
                <el-select v-model="form.paymentMethod" placeholder="请选择还款方式">
                  <el-option v-for="dict in credit" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple-light">
              <el-form-item label="贷款期限" prop="loanTerm">
                <el-select v-model="form.loanTerm" placeholder="请输入期数">
                  <el-option v-for="dict in term" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple">
              <div class="grid-content bg-purple">
                <el-form-item label="贷款金额" prop="applymoney">
                  <el-input type="number" v-model="form.applymoney" placeholder="请输贷款金额"></el-input>
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <div class="grid-content bg-purple-light">
        <label style="font-size: 20px;line-height: 50px;">还款总额<label
            style="margin-left: 100px;font-size: 35px;color: red;">{{ money }}元</label></label>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
  import { listProducts, searchProduct, verifInfo,calculate } from "@/api/credit/creproduct.js";
  import { log } from "console";
  
  export default {
    name: "Product",
    data() {
      return {
        // 等待时间
        timer: 0,
        // 还款金额
        money: '',
        sendM:'',
        //还款方式
        credit: '',
        //贷款期限
        term: '',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 产品表格数据
        productsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 5,
          id: '',
          productName: '',
          escrow: '',
  
        },
        // 表单参数
        form: {
          id: null,
          productId: null,
          productName: null,
          escrow: null,
          monthRate: null,
          consultingRate: 0,
          marginRate: 0,
          paymentMethod: null,
          loanTerm: null,
          applymoney: 0.0,
        },
        // 表单校验
        rules: {
          //   applymoney: [
          //   { required: true, message: "用户名称不能为空", trigger: "blur" },
          //   {  message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
          // ],
        }
      };
    },
    created() {
      this.getList();
      this.getDicts('cre_payment_method').then(res => {
        this.credit = res.data
        // console.log('zidian',res);
        // console.log(res);
      })
      this.getDicts('cre_loan_term').then(res => {
        this.term = res.data
        // console.log('zidian',res);
        // console.log(res);
      })
    },
    watch:{
			form:{
				// 此处监听obj属性a值变量
				handler(item1,item2){
          this.sendM = this.form.applymoney;
					// item1为新值，item2为旧值
          // 等待时间
          if (this.timer === 0) {
            this.timer = setTimeout(() => {
              this.getMoney();
            }, 1000)
          } else {
            clearTimeout(this.timer)
            this.timer = setTimeout(() => {
              this.getMoney();
            }, 1000)
          }
				},
				deep:true
			}
		},
    methods: {
      getMoney(){
       let data= {
          loanAmount:this.sendM, 
          monthlyRate:this.form.monthRate,
          marginRate:this.form.marginRate,
          consultingFeeRate:this.form.consultingRate,
          loanTerm:this.form.loanTerm,
          method:this.form.paymentMethod
        }
        calculate(data).then(res=>{
          this.money = res.data[0]
        }).catch();
      },
      /** 查询产品列表 */
      getList() {
        this.loading = true;
        listProducts(this.queryParams).then(response => {
          this.productsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
  
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          productName: null,
          escrow: null,
          monthRate: 0,
          consultingRate: 0,
          marginRate: 0,
          paymentMethod: 0,
          loanTerm: 0
  
        };
        this.resetForm("form");
      },
      search() {
        searchProduct(this.queryParams).then(res => {
          this.productsList = res.rows;
          this.total = res.total;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.search();
  
      },
  
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
  
  
      /** 购买按钮操作 */
      buy(row) {
        this.money=0
        this.open = true;
        this.form.id = row.id;
        this.form.productName = row.productName;
        this.form.escrow = row.escrow;
        this.form.monthRate = row.monthRate;
        this.form.consultingRate = row.consultingRate;
        this.form.marginRate = row.marginRate;
        this.form.paymentMethod = row.paymentMethod;
        this.form.loanTerm = row.loanTerm;
  
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          // if (valid) {
          //   if (this.form.id != null) {
          //     updateProducts(this.form).then(response => {
          //       this.$modal.msgSuccess("修改成功");
          //       this.open = false;
          //       this.getList();
          //     });
          //   } else {
          //     addProducts(this.form).then(response => {
          //       this.$modal.msgSuccess("新增成功");
          //       this.open = false;
          //       this.getList();
          //     });
          //   }
          // }
          //console.log(this.form.user_id);
          this.form.productId = this.form.id;
          // 购买
          verifInfo(this.form).then(res => {
            console.log(res);
            if(res.data==5001){
              this.$modal.msgSuccess(res.msg);
              this.open = false;
            }
            if(res.data == 5000){
              this.$modal.msgSuccess(res.msg);
              this.$router.push({ path: 'user/Profile' })
            }
            if (res.data == 1) {
              this.$modal.msgSuccess(res.msg);
              this.open = false;
              

            }
          }).catch(() => {
            this.$router.push({ path: '/credit_user/info/user/profile' })
          });
        });
      },
  
  
  
    }
  };
  </script>
  